package com.example.designPatterns.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * @Title: Observer
 * @Description: TODO
 * @Date 2019/8/8 17:25
 */
public class WechatServer implements IObserverAble {


    //注意到这个List集合的泛型参数为Observer接口，设计原则：面向接口编程而不是面向实现编程
    private List<Observer> list;
    private String message;

    public WechatServer() {
        list = new ArrayList<>();
    }

    @Override
    public void registerObserver(Observer o) {
        list.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
        if (null != list && !list.isEmpty()) {
            list.remove(o);
        }
    }

    @Override
    public void notifyObserver() {
        list.forEach(r -> r.push(this.message));
    }

    public void sendMsg(String s) {
        this.message = s;
        System.out.println("微信服务更新消息： " + s);
        //消息更新，通知所有观察者
        this.notifyObserver();
    }
}
